<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Advertising_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
	}
	
	function add_edit_submit(){
		if(!isset($_POST['id'])){
			if(!isset($_FILES["image"]) || empty($_FILES["image"]['name'])){
				echo "Image is required";exit();
			}
			
			$newId = $this->advertising_entity->createNewEntity();
			$ADV = $this->advertising_entity->init('id',$newId);
			
			$image = '';
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
								$_FILES["image"]['tmp_name'],
								$_FILES["image"]['name'],
								$ADV->getAdvFileDir(),
								allowExtensionPictureUpload()
							);
				}	
			}
			if(!$image){
				$this->db->where('id',$ADV->getId())->delete(TBL_ADVERTISING);
				echo "Image is required";exit();
			}
			
			$ADV->setUrl($_POST['url']);
			$ADV->setOrdering(intval($_POST['ordering']));
			$ADV->setImage($image);
			$ADV->setPosition($_POST['position']);
			$ADV->setClick(0);
			
			$ADV->update();
		}else{
			$ADV = $this->advertising_entity->init('id',$_POST['id']);
			$image = $ADV->getImage();
			
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
								$_FILES["image"]['tmp_name'],
								$_FILES["image"]['name'],
								$ADV->getAdvFileDir(),
								allowExtensionPictureUpload()
							);
				}	
			}
			if(!$image){
				echo "Image is required";exit();
			}
			
			$ADV->setUrl($_POST['url']);
			$ADV->setOrdering(intval($_POST['ordering']));
			$ADV->setImage($image);
			$ADV->setPosition($_POST['position']);
			
			$ADV->update();
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}
	
	function delete(){
		$this->db->where('id',$_POST['id'])->delete(TBL_ADVERTISING);
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}
	
	function change_status(){
		$ADV = $this->advertising_entity->init('id',$_POST['id']);
		$new_status = ($ADV->getStatus() == 'show') ? 'hide':'show';
		$ADV->setStatus($new_status);
		$ADV->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}
//end class	
}	